<?php


namespace App\Services;


use App\Models\Permission;
use App\Models\User;
use App\Service\Service;
use Carbon\Carbon;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Tymon\JWTAuth\JWTGuard;

/**
 * Class AuthServices
 * @property string $username
 * @property string $password
 * @package App\Services
 * @author thanatos thanatos915@163.com
 */
class AuthService extends Service
{

    /**
     * 用户登录
     * @author thanatos thanatos915@163.com
     */
    public static function Login(Request $request)
    {
        $service = static::loadParams($request, [
            'username' => 'required',
            'password' => 'required',
        ]);

        $user = User::whereUsername($service->username)->first();

        if (empty($user)) {
            throw new BadRequestHttpException("用户不存在");
        }

        if ($user->status == User::STATUS_FREEZE) {
            throw new BadRequestHttpException("用户已被冻结无法登录");
        }

        if (!$user->checkPassword($service->password)) {
            throw new BadRequestHttpException("密码不正确");
        }

        // 生成Token

        /** @var JWTGuard $guard */
        $guard = app()['auth']->guard();
        $token = $guard->login($user);

        if (empty($token)) {
            throw new BadRequestHttpException("Token生成失败");
        }

        //
        $user->last_login_at = Carbon::now();
        $user->save();

        return [
            'id' => $user->id,
            'username' => $user->username,
            'realname' => $user->realname,
            'status' => $user->status,
            'last_login_at' => $user->last_login_at,
            'token' => $token
        ];
    }

    public static function info()
    {
        $id = get_user_id();

        $user = User::find($id);

        if (isAdmin()) {
            $permissions = Permission::get();
        } else {
            $permissions = $user->getAllPermissions();
        }

        $data = [];
        foreach ($permissions as $item) {
            array_push($data, $item->name);
        }

        $user['roles'] = [
            'permissions' => $data
        ];
        return $user;
    }

}
